//
//  WBMainViewController.swift
//  仿写微博
//
//  Created by Apple on 17/6/30.
//  Copyright © 2017年 tuimao. All rights reserved.
//

import UIKit
import SVProgressHUD
class WBMainViewController: UITabBarController {
    //撰写按钮添加
   fileprivate lazy var composeButton:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    //设置刷新未读微博的计时器
    fileprivate lazy var time:Timer = Timer()
    //初始化
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置子控制器
        setupChildControllers()
        //设置撰写按钮
        setupcomposeButton()
        //定期检查微博数量
        setupTimer()
        //设置新特性视图
        setupNewfeatureViews()
        //设置代理
        delegate = self
        //接受微博登录的通知
        NotificationCenter.default.addObserver(self, selector: #selector(userlogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    deinit {
        time.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
    /*
     portrait  竖屏
     landscape 横屏
     
     */
    // -使用代码控件设置设备的方向，好处，可以在需要横屏的时候，单独处理
    // -设置支持的方向后，当前的控制器及子控制器都会遵守这个方向！
    // -如果播放视频，通常是通过modal展现
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        
        return .portrait
    }
    //中间撰写微博的点击事件
    //FIXME:点击事件
    @objc fileprivate func composeStatus(){
        let composeVC = WBComposeTypeView.ComposeTypeView()
        //展示视图
        composeVC.show {[weak composeVC] (clsName) in
            
            guard let clsName = clsName,
                let cls = NSClassFromString(Bundle.main.namespace + "." + clsName)as? UIViewController.Type
                else{
                    return
            }
            let vc = cls.init()
            let nvc = UINavigationController.init(rootViewController: vc)
            self.present(nvc, animated: true, completion: { 
                composeVC?.removeFromSuperview()
            })
        }
    }
    //登录通知的点击事件
    //FIXME:点击事件
    @objc fileprivate func userlogin(n:Notification){
        var when = DispatchTime.now()
        if n.object != nil {
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "用户登录已经超时，请重新登录")
            when = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) { 
            SVProgressHUD.setDefaultMaskType(.clear)
            let nav = UINavigationController(rootViewController: WBOAuthViewController())
            self.present(nav, animated: true, completion: nil)
            print("登录微博的通知")
        }
        
    }
}

//MARK:设置新特性视图
extension WBMainViewController{
    //设置新特性视图
    fileprivate func setupNewfeatureViews(){
     //是否是新特性
        let v = isNewVersion ? WBNewFeature.WBNewFeature() : WBWelcomeView.welcomeView()
        view.addSubview(v)
    }
    //计算型属性
    private var isNewVersion:Bool{
        //1.取当前的版本号
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        //2.取出保存（document，但是一般存在用户偏好中）目录中的版本号
        let path = ("version" as NSString).cz_appendDocumentDir() ?? ""
        let sendBoxVersion = (try? String(contentsOfFile: path)) ?? ""
        //3.将当前版本号保存在沙盒中
        _ = try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        //4.返回两个版本号是否一致
        return currentVersion != sendBoxVersion
    }
}


//MARK:UITabBarControllerDelegate
extension WBMainViewController : UITabBarControllerDelegate{
    //使用这个方法纠正中间按钮点击不正确的问题
    /// 将要选择tabbarItem
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController
    ///   - viewController: 将要跳转到的目标控制器
    /// - Returns: 返回目标控制器
    public func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool{
        //点击的控制器
        let idx = childViewControllers.index(of: viewController)
        //如果选择控制器  和 当前的控制器一致且都为 home【0】那么生效
        if selectedIndex == 0 && idx == selectedIndex {
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            print(viewController)
            //回到顶部，注意inset缩进
            vc.tableView?.setContentOffset(CGPoint(x:0,y:-64), animated: true)
            //刷新数据
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                vc.loadData()
            })
            //把提示制空
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        
        return !viewController.isMember(of: UIViewController.self)
    }
    
    
}

//MARK:  时钟
extension WBMainViewController{
    //设置定时器
    fileprivate func setupTimer(){
        time = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
    }
    //未读数据请求
    @objc private func updateTime(){
        if !WBNetworkManager.shared.userlogon {
            return
        }
        //测试未读数据
        WBNetworkManager.shared.unreadCount { (count) in
            //在tabarItem上显示提示
            self.tabBar.items?[0].badgeValue = count > 0 ? " \(count)" : nil
            //在app图标上显示消息数量
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}


//MARK:  页面初始化设置
extension WBMainViewController{
    //设置撰写按钮
    fileprivate func setupcomposeButton()  {
        tabBar.addSubview(composeButton)
        //计算按钮的宽度
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width / count
        //CGRectInset正数向内缩进，负数向外
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        //撰写按钮点击事件
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
        
    }
     /// 设置子控制器（有些公司这一部分UI数据会从服务器获取，方便更改）
     fileprivate func setupChildControllers() {
        //查看本地沙盒数据
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonpath = (docDir as NSString).appendingPathComponent("main.json")
        var data = NSData(contentsOfFile: jsonpath)
        //如果沙盒没有数据，就加载
        if data == nil {
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: Any]]
        else{
                            return
        }
        
        //控制器数组
        var arrayM = [UIViewController]()
        //遍历添加数组
        for dic in array! {
            arrayM.append(controller(dict: dic))
        }
        //赋值TabbarVC的控制器数据
        viewControllers = arrayM
     }
    
    /// 设置子控制器的title，image
    ///
    /// - Parameter dict: 字典
    /// - Returns: 一个控制器
    private func controller(dict:[String:Any]) -> UIViewController {
        guard let clsName = dict["clsName"] as? String,
                  let title = dict["title"] as? String,
                  let image = dict["image"] as? String,
                  let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
                  let visitorDict = dict["visitorInfo"] as? [String:String]
        else {
                return UIViewController()
             }
        let vc = cls.init()
        vc.visitorInfoDict = visitorDict
        vc.title = title
        //"tabbar_home_selected"
        vc.tabBarItem.image = UIImage(named:"tabbar_" + image)
        vc.tabBarItem.selectedImage = UIImage(named:"tabbar_" + image + "_selected")?.withRenderingMode(.alwaysOriginal)
        //设置tabBarTitle的字体颜色
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: UIControlState(rawValue: 0))
        let nav = WBNavigationController(rootViewController: vc)
        return nav
    }
    
}
